﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DosciWordPlugin.Common;
using DosciWordPlugin.Models;
using Newtonsoft.Json;

namespace DosciWordPlugin.Controls
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string username = txtUsername.Text.Trim();
                string password = txtPassword.Text.Trim();

                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    WinApp.MsgBoxInfo("Email 和 Password 不能为空！");
                    return;
                }

                btnLogin.Enabled = false;
                Cursor = Cursors.WaitCursor;

                Dictionary<string, string> dicParam = new Dictionary<string, string>();
                dicParam.Add("username", username);
                dicParam.Add("password", password);

                User user = HttpUtil.Post<User>(Constant.API_登陆, dicParam);
                if (user != null && !string.IsNullOrEmpty(user.Token)) 
                {
                    CacheManager.SetUserInfo(user);
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                WinApp.MsgBoxError(ex.Message);
            }
            finally
            {
                btnLogin.Enabled = true;
                Cursor = Cursors.Arrow;
            }
        }
    }
}
